﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
using MaiPlanServer.Utility;
using MaiPlanServer.IServices.IEquipmentServices;
using MaiPlanServer.Model;
using System.Linq;
using MaiPlanServer.Dto;

namespace MaiPlanServer.API.Controllers.Equipment
{
    [Route("api/[controller]")]
    [ApiController]
    public class DeviceTypeController : ControllerBase
    {


        public DeviceTypeController(IDeviceTypeServices DtDb)
        {
            this.DtDb = DtDb;
        }
        public IDeviceTypeServices DtDb { get; }

        /// <summary>
        /// 获取设备类型名称
        /// </summary>
        /// <param name="PageIndex">当前页数</param>
        /// <param name="PageSize">每页显示条数</param>
        /// <param name="mtName">规则名称</param>
        /// <param name="enable_flag">是否启用</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get(int PageIndex, int PageSize, string mtName,string enable_flag)
        {
            try
            {
                List<dv_machinery_typeDto> DList = new List<dv_machinery_typeDto>();
                if (string.IsNullOrEmpty(enable_flag))
                {
                    enable_flag = "";
                }

                var list = await DtDb.GetJsonAsync(PageIndex,PageSize, mtName, enable_flag);
                DList = GetItem(list);
                var count = await DtDb.GetCountAsync(mtName);

                return Ok(BaseState.CreateInstance(200, "请求成功", DList, count));
            }
            catch (Exception ex)
            {
                return Ok(BaseState.CreateInstance(BaseState.RequestError, "请求失败ex"));
            }
        }

        /// <summary>
        /// 添加设备类型名称
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] dv_machinery_type model)
        {
            try
            {
                if (!string.IsNullOrEmpty(model.machinery_type_name))
                {
                    model.machinery_type_id = Guid.NewGuid().ToString();
                    model.create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    model.machinery_type_code = await DtDb.GetCodeasync("设备类型编码");
                    
                    var add = await DtDb.AddAsync(model);

                    return Ok(new { code = 200, msg = "请求成功" });
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return Ok(new { code = -1, msg = "请求失败", count = 0, data = "" });
        }

        /// <summary>
        /// 修改设备类型设置
        /// </summary>
        /// <param name="model">部门模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Put([FromForm] dv_machinery_type model)
        {
            try
            {
                model.update_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var result = await DtDb.UpdateAsync(model);
                if (result)
                {
                    return Ok(BaseState.CreateInstance(200, "修改成功"));
                }
            }
            catch (System.Exception ex)
            {
                //后续写日志
            }
            return Ok(BaseState.CreateInstance(-1, "修改失败，服务器异常"));
        }

        /// <summary>
        /// 删除设备类型名称
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del(string Id)
        {
            try
            {
                var model = await DtDb.DellAsync(Id);
                if (model)
                {
                    return Ok(BaseState.CreateInstance(200, "删除成功"));
                }
                return Ok(BaseState.CreateInstance(-1, "删除失败"));
            }
            catch (Exception ex)
            {
                return Ok(BaseState.CreateInstance(-1, "删除失败"));
            }
        }


        /// <summary>
        /// 删除多条设备类型名称
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll(string Id)
        {
            try
            {
                string[] Ids = Id.Split(',');
                var model = await DtDb.DellAllAsync(Ids);
                if (model)
                {
                    return Ok(BaseState.CreateInstance(200, "删除成功"));
                }
                return Ok(BaseState.CreateInstance(-1, "删除失败"));
            }
            catch (Exception ex)
            {
                return Ok(BaseState.CreateInstance(-1, "删除失败"));
            }
        }


        [NonAction]
        private List<dv_machinery_typeDto> GetItem(IEnumerable<dv_machinery_typeDto> list)
        {
            List<dv_machinery_typeDto> TreeList = new List<dv_machinery_typeDto>();
            var parent = list.Where(x => string.IsNullOrEmpty(x.parent_type_id));
            var child = list.Where(x => !string.IsNullOrEmpty(x.parent_type_id));
            var t = child.ToList();
            foreach (var item in parent)
            {
                //判断当前父元素有没有子元素
                var curr_child = child.Where(x => x.parent_type_id == item.machinery_id);
                if (curr_child.Any())
                {
                    GetSubItem(item, list, curr_child);
                }
                TreeList.Add(item);
            }
            return TreeList;
        }
        [NonAction]
        public void GetSubItem(dv_machinery_typeDto parent, IEnumerable<dv_machinery_typeDto> list, IEnumerable<dv_machinery_typeDto> child)
        {
            foreach (var item in child)
            {
                var curr_child = list.Where(x => x.parent_type_id == item.machinery_id);
                if (curr_child.Any())
                {
                    GetSubItem(item, list, curr_child);
                }

                parent.Children.Add(item);
            }
        }


    }
}
